// pages/restaurant/restaurant.js
const util = require('../../utils/util.js');
var app = getApp();
var WxParse = require('../../lib/wxParse/wxParse.js');
var api = require('../../config/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:0,
    categoryId:0,
    goodsId:0,
    info:{},
    storeCategoryVoList:[],
    activeNames: [0],
    isJiuCan: false,
    dating: '大厅',
    desk: '',
    foods: [],
    orderRange:"1",
    preference:'',
    orderPhone:'',
    orderNick:'',
    canOrderRangeList:[],
    canOrder:true,
    foodNums: {
      // 1: 2
    },
    selectedFoods: [
      // {name: '红烧鲍鱼', price: '67.00', num: 1, total: '67.00'}
    ],
    selectedTotalSum: '0',
    seatList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
   
    util.request(api.StoreDetail, {
      id: options.id
    }).then(function(res) {
      if (res.errno === 0) {
        //过滤空类型
        res.data.storeCategoryVoList =  res.data.storeCategoryVoList.filter(cate=>cate.goodsVoList.length>0);
        if( res.data.storeCategoryVoList)
        {
          res.data.storeCategoryVoList.forEach((cate)=>{
            cate.goodsVoList.forEach(goods=>{
              goods.name = goods.name.substring(0,10)
            })
          })
        }
        if(options.categoryId){
          //去找到该商品的类别索引号
          let selectedCategoryIndex = res.data.storeCategoryVoList.findIndex(c=>parseInt(options.categoryId)===c.id);
          let selectedIndex = [];
          selectedIndex.push(selectedCategoryIndex);

          
          that.setData({
            id: parseInt(options.id),
            categoryId : parseInt(options.categoryId),
            info: res.data.info,
            storeCategoryVoList: res.data.storeCategoryVoList,
            activeNames:selectedIndex
          });
        }else{
          that.setData({
            id: parseInt(options.id),
            info: res.data.info,
            storeCategoryVoList: res.data.storeCategoryVoList,
          });

          that.querySeatList();
          
          
        }
      }
    });
   
  },
  querySeatList:function(){
     //根据条件查询座位
     let that = this;

    util.request(api.SeatList, {
      storeId: that.data.id,
      type:that.data.dating,
      orderRange:that.data.orderRange
    }).then(function(res) {
      if (res.errno === 0) {
        if(res.data.seatList&&res.data.seatList.length>0){
          res.data.seatList.forEach(seat=>{
            seat.desk = seat.minCount +'-'+seat.maxCount;
            if(!seat.images||seat.images.length==0){
              seat.pic = "./images/default.jpg"
              // seat.images=[]
              // seat.images[0]=seat.pic
            }
            else{
              seat.pic = seat.images[0];
            }
            if(!seat.characteristic){
              seat.characteristic = '待录入特色'
            }
            
          })
          that.setData({
            // desk:res.data.seatList[0].id,
            seatList: res.data.seatList
          });
          // that.checkSeat();
        }
        else{
          that.setData({
            // desk:res.data.seatList[0].id,
            seatList: []
          });
          util.showErrorToast('无可选座位');
        }
       
      }
    });
  },
  showImages(e){
    let seat = e.currentTarget.dataset.seat;
    if(seat.images&&seat.images.length>0){
      wx.previewImage({
        current:  seat.pic, // 当前显示图片的http链接
        urls: seat.images// 需要预览的图片http链接列表
      })
    }else{
      util.showErrorToast('商家还未上传图片');
    }
  },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this;
   
  },

  onLaunch() {
    //console.log('onLaunch监听小程序初始化');
  },
  back(){
    wx.navigateBack({
      delta: 1
    })
  },
  bindOrderPhoneInput: function(e) {
    this.setData({
      orderPhone: e.detail.value
    });
  },
  bindOrderNickInput: function(e) {
    this.setData({
      orderNick: e.detail.value
    });
  },
  bindPreferenceInput: function(e) {
    this.setData({
      preference: e.detail.value
    });
  },
  getStoreInfo: function() {
    let that = this;
    util.request(api.StoreDetail, {
      id: that.data.id
    }).then(function(res) {
      if (res.errno === 0) {
        that.setData({
          info: res.data.info,
          storeCategoryVoList: res.data.storeCategoryVoList
        });
        
      }
    });
  },
  collapseOnChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },

  jiucan: function() {
    this.setData({
      isJiuCan: true
    });

    // this.checkSeat();
  },
  checkSeat(){
    if(this.data.isJiuCan){
      let that = this;
      util.request(api.CheckSeat, {
        storeId: that.data.id,
        type:that.data.dating,
        seatId:that.data.desk,
        orderRange:that.data.orderRange
      }).then(function(res) {
        if (res.errno === 0) {
          console.log(res.data);
          let seatId = res.data.seatId;
          let hasSeat = seatId!=0;
          that.setData({
            canOrder:hasSeat,  //true：可定做
            desk:seatId
          });
          if (!that.data.canOrder) {
            util.showErrorToast('该时段已预订');
          }
        }
      }); 
    }
  },
  datingChange: function (event) {
    
    this.setData({
      dating: event.currentTarget.dataset.v
    });
    this.querySeatList();

  },
  orderRangeChange: function (event) {
    this.setData({
      orderRange: event.currentTarget.dataset.v
    });
    this.querySeatList();

  },
  submitOrder: function(event) {
    let that = this;
    if (!this.data.canOrder) {
      util.showErrorToast('已满座');
      return false;
    }
    if (this.data.desk===0||this.data.desk==="") {
      util.showErrorToast('请先选桌');
      return false;
    }
    if (this.data.selectedFoods.length===0) {
      util.showErrorToast('请先点菜');
      return false;
    }

    if (!this.data.orderPhone) {
      util.showErrorToast('请填写订餐电话');
      return false;
    }
    //过滤字段
    let foods = this.data.selectedFoods.map(function(foods){
     return {
      id:foods.id,
      num : foods.num
    }
   });

   let type = event.currentTarget.dataset.v;

    util.request(api.OrderSubmit, {
      type: type,
      message: this.data.message,
      dating: this.data.dating,
      orderRange: this.data.orderRange,
      selectedFoods: JSON.stringify(foods),
      storeId:this.data.id,
      seatId:this.data.desk,
      preference:this.data.preference,
      orderPhone:this.data.orderPhone,
      orderNick:this.data.orderNick
    }, 'POST').then(res => {
      if (res.errno === 0) {

        // 下单成功，重置couponId
        try {
          wx.setStorageSync('couponId', 0);
        } catch (error) {

        }

        const orderId = res.data.orderId;
        const grouponLinkId = res.data.grouponLinkId;

        
        //如果是到店支付就不用支付了
        if(type==="3"){
          wx.showModal({
            title: '温馨提示',
            content: '到店支付将不会留座，如需留座请选择订金/全额订座',
            success (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/noPayResult/noPayResult?message=预订成功&status=1&orderId=' + orderId
                });
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
         
        }
        else{
          util.request(api.OrderPrepay, {
            orderId: orderId
          }, 'POST').then(function(res) {
            if (res.errno === 0) {
              const payParam = res.data;
              console.log("支付过程开始");
              wx.requestPayment({
                'timeStamp': payParam.timeStamp,
                'nonceStr': payParam.nonceStr,
                'package': payParam.packageValue,
                'signType': payParam.signType,
                'paySign': payParam.paySign,
                'success': function(res) {
                  console.log("支付过程成功");
                  if (grouponLinkId) {
                    setTimeout(() => {
                      wx.redirectTo({
                        url: '/pages/groupon/grouponDetail/grouponDetail?id=' + grouponLinkId
                      })
                    }, 1000);
                  } else {
                    wx.redirectTo({
                      url: '/pages/payResult/payResult?status=1&orderId=' + orderId
                    });
                  }
                },
                'fail': function(res) {
                  console.log("支付过程失败");
                  wx.redirectTo({
                    url: '/pages/payResult/payResult?status=0&orderId=' + orderId
                  });
                },
                'complete': function(res) {
                  console.log("支付过程结束")
                }
              });
            } else {
              wx.redirectTo({
                url: '/pages/payResult/payResult?status=0&orderId=' + orderId
              });
            }
          });
        }

        

      } else {
        util.showErrorToast(res.errmsg);
      }
    });
  },
  deskChange: function (event) {
    this.setData({
      desk: event.currentTarget.dataset.id
    });
    this.checkSeat();
  },

  //联系商家
  lianxi: function (event) {
    wx.makePhoneCall({
      phoneNumber: event.currentTarget.dataset.mobile,
    })
  },
  //导航前往
  daohang: function (event) {
    let that = this;
    let latLon  = this.data.info.latLon.split(",");
    let latitude = parseFloat(latLon[0]);
    let longitude = parseFloat(latLon[1]);
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        wx.openLocation({//​使用微信内置地图查看位置。
          latitude: latitude,//要去的纬度-地址
          longitude: longitude,//要去的经度-地址
          name: that.data.info.name,
          address: that.data.info.address
        })
      },
      fail: function(res) {
        console.log(res)
        if (res.errMsg == 'getLocation:fail auth deny') {
          util.showErrorToast('未授权位置权限');
        }
      }
    })
  },

  numMinus: function (event) {
    this.jiucan();
    const id = event.currentTarget.dataset.id;
    let n = { ...this.data.foodNums };
    if (n[id] != undefined) {
      if (n[id] - 1 <= 0) {
        delete n[id];
      } else {
        n[id]--;
      }
      this.selectFoodsChange(n);
      this.setData({
        foodNums: n
      });
    }
  },

  numPlus: function (event) {
    this.jiucan();
    const id = event.currentTarget.dataset.id;
    let n = { ...this.data.foodNums };
    if (n[id] != undefined) {
      n[id]++;
    } else {
      n[id] = 1;
    }
    this.selectFoodsChange(n);
    this.setData({
      foodNums: n
    });
  },

  //计算所选菜品
  selectFoodsChange: function(n) {
    let foodsHash = {};
    this.data.storeCategoryVoList.forEach(category=>{
      category.goodsVoList.forEach(goods=>{
        foodsHash[goods.id] = goods;
      })
    })
 
    let selectedFoods = [];
    let selectedTotalSum = 0;
    for (let id in n) {
      let num = n[id];
      selectedFoods.push({
        id: foodsHash[id].id,
        name: foodsHash[id].name,
        price: foodsHash[id].counterPrice.toFixed(2),
        num,
        total: (foodsHash[id].counterPrice * num).toFixed(2)
      });
      selectedTotalSum += foodsHash[id].counterPrice * num;
    }
    this.setData({
      selectedTotalSum,
      selectedFoods
    });
  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})